package appcus

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/customer"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

type AppCusOrderPayService struct{}

func (p *AppCusOrderPayService) AppOrderPay(orderId, fee string) (err error) {
	var order customer.CusOrder
	// 查询记录，检查 is_paid 是否已经是 1
	err = global.GVA_DB.Model(&customer.CusOrder{}).
		Where("id = ? AND status = 4 AND ex_price = ? AND is_paid = ?", orderId, fee, 1).
		First(&order).Error

	// 如果已存在 is_paid = 1 的记录，返回提示
	if err == nil {
		return fmt.Errorf("订单已经标记为已支付")
	} else if errors.Is(err, gorm.ErrRecordNotFound) {
		// 如果没有找到符合条件的记录，执行更新操作
		err = global.GVA_DB.Model(&customer.CusOrder{}).
			Where("id = ? AND status = 4 AND ex_price = ?", orderId, fee).
			Update("is_paid", 1).Error
		if err != nil {
			return fmt.Errorf("更新订单失败: %v", err)
		}
	} else {
		// 如果查询时出错，返回错误
		return fmt.Errorf("查询错误: %v", err)
	}

	return nil
}
